const express = require(`express`);

const router = express.Router();

// 导入模块model
const query = require(`../model/query-promise.js`)

router.get(`/cate`, async (req, res) => {
    let sql = `select * from category where is_show = 1`;
    let result = await query(sql)
    res.json( result )
})
//获取首页分页文章
router.get(`/article`, async (req, res) => {
    let { page = 1, pagesize = 3 } = req.query;
    //起始位：（当前页-1）* 每页显示的条数
    let offset = (page - 1) * pagesize;
    let sql = `select t1.*,t2.cate_name from article t1 left join category t2 on t1.cat_id = t2.cate_id
     where t1.is_delete = 0 and t1.status = 1 limit ${offset},${pagesize}`
    let result = await query(sql)
    res.json({ result })
    // res.send(result)
})

//获取文章详情
router.get(`/detail`, async (req, res) => {
    let { id } = req.query;
    id = parseInt(id);
    id = isNaN(id) ? 0 : id;
    let sql = `select t1.*,t2.cate_name from article t1 left join category t2 on t1.cat_id = t2.cate_id where t1.id =${id}`;
    let result = await query(sql)
    res.json(result[0] || {})
})

//获取指定分类下的文章表
router.get(`/cateArticle`, async (req, res) => {
    let { page = 1, pagesize = 2, cat_id} = req.query;

    let offset = (page - 1) * pagesize;
    let sql = `select t1.*, t2.cate_name from  article t1 left join category t2 on t1.cat_id = t2.cate_id
    where t1.status = 1 and t1.cat_id= ${cat_id} limit ${offset},${pagesize} `
    let result = await query(sql)
    console.log(result)
    res.json(result)
})

router.get(`*`, (req, res) => {
    res.json({ message: `404` })
})

module.exports = router;